import { useState, useEffect } from 'react';
import { useDrag } from 'react-dnd';
import { FolderOutlined, FolderOpenOutlined, FunctionOutlined } from '@ant-design/icons';
import { Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { useFlowStore } from '../../stores/flowStore';
import './FunctionPalette.css';

interface FunctionDefinition {
  id: string;
  name: string;
  category?: string;
  parameters: any[];
  execute: (params: any) => Promise<any>;
}

// 动态加载所有函数模块（Vite专用语法）
const loadFunctionModules = async () => {
  const modules = import.meta.glob('../../functions/*/*.js');
  const loadedFunctions: FunctionDefinition[] = [];
  for (const path in modules) {
    try {
      const mod = await modules[path]();
      const folderName = path.split('/')[3]; // 提取文件夹名（如 KPMS_Commands）
      loadedFunctions.push({
        id: path.split('/')[4], // 生成唯一ID
        name: path.split('/')[4],
        category: folderName,
        parameters: mod.meta?.parameters || [],
        execute: mod.default
      });
    } catch (error) {
      console.error(`加载模块失败: ${path}`, error);
    }
  }

  return loadedFunctions;
};

// 构建树形数据结构（完全自动根据文件夹分类）
const buildTreeData = (functions: FunctionDefinition[]): DataNode[] => {
  const groupMap = new Map<string, FunctionDefinition[]>();

  // 按文件夹分组
  functions.forEach(func => {
    const category = func.category || '未分类';
    if (!groupMap.has(category)) {
      groupMap.set(category, []);
    }
    groupMap.get(category)!.push(func);
  });

  // 转换为AntD的树结构
  return Array.from(groupMap.entries()).map(([folder, funcs]) => ({
    title: folder.replace(/_/g, ' '), // KPMS_Commands -> "KPMS Commands"
    key: folder,
    icon: ({ expanded }: { expanded: boolean }) => 
      expanded ? <FolderOpenOutlined /> : <FolderOutlined />,
    children: funcs.map(f => ({
      title: f.name,
      key: f.id,
      isLeaf: true,
      icon: <FunctionOutlined />,
      functionDef: f
    }))
  }));
};

// 可拖拽的函数项组件
const FunctionItem = ({ item }: { item: DataNode }) => {
  const [, drag] = useDrag(() => ({
    type: 'FUNCTION',
    item: { func: item.functionDef }
  }));

  return (
    <div ref={drag} className="function-item" style={{ cursor: 'grab' }}>
      {item.title}
    </div>
  );
};

export const FunctionPalette = () => {
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const { functions, setFunctions } = useFlowStore();

  useEffect(() => {
    const loadModules = async () => {
      if (functions.length === 0) {
        const loaded = await loadFunctionModules();
        setFunctions(loaded);
        setTreeData(buildTreeData(loaded));
      } else {
        setTreeData(buildTreeData(functions));
      }
    };
    loadModules();
  }, [functions, setFunctions]);

  // 自定义树节点渲染
  const renderTitle = (node: DataNode) => {
    if (node.children) {
      return <span style={{ marginLeft: 4 }}>{node.title}</span>; // 文件夹节点
    }
    return <FunctionItem item={node} />; // 函数节点
  };

  return (
    <div className="function-palette" style={{ padding: '5px' }}>
      <Tree
        defaultExpandAll
        treeData={treeData}
        titleRender={renderTitle}
        selectable={false}
      />
    </div>
  );
};